package org.kev.transit;

import java.util.*;

import org.kev.transit.data.RouteType;
import org.kev.transit.util.TransitConst;
import org.kev.transit.util.TransitUtil;
import org.kev.transit.worker.DataWorker;


import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.database.Cursor;

/**
 * Route type screen.  Examples could be Caltrain, BART etc.. 
 * The data displayed is based on a Web service(JSON) call that is then cached in
 * the local DB.  Someday it will also expire cached data in the DB.  All DB updates 
 * occur in a background thread.
 * @author kevin
 *
 */
public class Transit extends DataActivity{
	public static final int BACK_ID = FIRST_MENU+1;
	public static final int NEXT_ID = FIRST_MENU+ 2;
	public static final int SETTINGS_ID = FIRST_MENU + 3;
	public static final String TAG = "Transit";
	private ArrayAdapter <RouteType> arrayAdapter=null;
	/** Need handler for callbacks to the UI thread */
    private final Handler mHandler = new Handler();
    private final DataWorker mWorker = new DataWorker();
	private ListView mRouteTypeList=null;
    
	public Transit() {

	}

/**
 *  Called when fist started
 *  @param icicle
 */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		try {
			
			// Inflate our UI from its XML layout description.
			 requestWindowFeature(Window.FEATURE_PROGRESS);
			
			setContentView(R.layout.transit);
	        setProgressBarVisibility(true);
	        setProgressBarIndeterminate(true);
			
			Log.d(TAG,"INFLAGE XML!!!");
		    mRouteTypeList = (ListView) findViewById(R.id.routeTypeList);  
		    Log.d(TAG,"list="+mRouteTypeList);

			 mRouteTypeList.setOnItemSelectedListener(mRouteTypeListener );
			 mRouteTypeList.setOnItemClickListener(mItemListener);
			// Hook up button presses to the appropriate event handler.
			//((Button) findViewById(R.id.settings)).setOnClickListener(mSettingsListener);
			 

		} catch (Exception e) {
			Log.e(TransitConst.TAG,"UKNOWN Error in "+this,e);
			
			//TODO this should fail if it ever get calleD!
			AlertDialog.show(this,"StackTrace",1, e.getMessage(), "Ok", false);
					}
		Log.d(TAG,"end onCreate");
	}
	
	
	/**
	 * set the currently select rout item based on pref if it exist
	 * @param routeTypeSpin
	 */
	private void setCurrentRouteType(ListView routeTypeList) {
			Log.d(TAG,"setCurrentRouteType");
	       SharedPreferences settings = getSharedPreferences(TransitConst.PREFS_NAME, 0);
		   String current = settings.getString(TransitConst.ROUTE_TYPE_PREF,"");
		   Log.d(TAG,"current rt pref="+current+"|view="+mRouteTypeList);
		   ListAdapter adapt= mRouteTypeList.getAdapter();
		   Log.d(TAG,"adapt="+adapt);
		   int count =routeTypeList.getCount();
		   for (int i=0;i<count;i++){
			   String s =adapt.getItem(i).toString();
			   
			   if (s.equals(current) && s!=null){
				   Log.d(TransitConst.TAG,"found slection"+s);
				   routeTypeList.setSelection(i);
			   }
		   }
	}

	
	/**
	 * Called when the activity is about to start interacting with the user.
	 */
	@Override
	protected void onResume() {
		super.onResume();
		getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,Window.PROGRESS_VISIBILITY_ON);
		mWorker.init(this,mHandler,mUpdateResults);
		Thread t = new Thread(mWorker);
		t.setDaemon(true);
		t.start();
		Log.d(TransitConst.TAG,".onResume restore Prefs !");
		//setCurrentRouteType(mRouteTypeList);
		
		//call update spinners
		Log.d(TransitConst.TAG,".end onResume restore Prefs !");
	
	}
/**
 * 
 * I am being paused save all prefs
 */
	@Override
	protected void onPause() {
		super.onPause();
		
		Log.d(TransitConst.TAG,"onPAUSE Save Prefs!");
		Log.d(TransitConst.TAG,TransitConf.toXML() );
		TransitUtil.savePref(this,TransitConst.ROUTE_TYPE_PREF, TransitConf.currentRouteType);
	}
	
    @Override
    protected void onFreeze(Bundle outState) {
    	super.onFreeze(outState);
        // Remember state
      //  outState.putBundle("transit-view", mLunarView.saveState());
    }
	/**


	/**
	 * Called when your activity's options menu needs to be created.
	 * @param menu
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		// We are going to create two menus. Note that we assign them
		// unique integer IDs, labels from our string resources, and
		// given them shortcuts.

	//	menu.add(0, SETTINGS_ID, R.string.settings).setShortcut(
	//			KeyEvent.KEYCODE_1, 0, KeyEvent.KEYCODE_S);
		return true;
	}

	/**
	 * Called right before your activity's option menu is displayed.
	 *  @param menu
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);

		// Before showing the menu, we need to decide whether the clear
		// item is enabled depending on whether there is text to clear.
		// menu.setItemShown(CLEAR_ID, mEditor.getText().length() > 0);

		return true;
	}

	/**
	 * Called when a menu item is selected.
	 *  @param item
	 *  
	 */  
	@Override
	public boolean onOptionsItemSelected(Menu.Item item) {
		switch (item.getId()) {
		case BACK_ID:
			finish();
			return true;
		case NEXT_ID:
			nextScreen();
			return true;
		}

		return super.onOptionsItemSelected(item);
	}
	/**
	 * Jump to next Screen (StopActivity)
	 */
	public void nextScreen(){

		Log.d(TAG,"nextScreen!");
		startActivity(TransitConst.ROUTE_INTENT );
	}

	/**
	 * fill the ArrayAdaptor with data this is called by a worker thread
	 */
	public void setData(){
		Cursor cursor = null;
		try{
			Log.d(TAG,">>> begin setData");
				Uri curi  = Uri.parse("content://transit/route_type");
				cursor = managedQuery(curi, new String[] {RouteType._ID,RouteType.TITLE}, null, null);
				ArrayList <RouteType> list = RouteType.getData(this);
				arrayAdapter= new  ArrayAdapter <RouteType> (this,android.R.layout.simple_list_item_1,list);
		}catch(Exception e){
			Log.e(TAG,"setRouteType()",e);
		}finally{
			if (cursor!=null)
				cursor.close();
		}
		Log.d(TAG,"<<< end setData");
	}

	

	/**
	 * save selected item in a TransitConf object
	 */
	private void routeTypeSelected(){
		Log.d(TransitConst.TAG,"route type selected");
		//mRouteTypeSpin.getSelectedItem();
		if( mRouteTypeList.getSelectedItem()!=null){
			RouteType temp = (RouteType) mRouteTypeList.getSelectedItem();
			TransitConf.currentRouteType=temp.title;
			TransitConf.currentRouteTypeId=temp.id;
		}
		
	}

	//****************INNER CLASSES***********************************
	   // Create runnable for posting
  
  
    /**
     *  Create runnable for posting
     */
   Runnable mUpdateResults = new Runnable() {

    	public void run() {
    		Log.d(TAG,"set mUpdateResults.run()=");
    		mRouteTypeList.setAdapter(arrayAdapter);
    		setCurrentRouteType(mRouteTypeList);
    		 setProgressBarVisibility(false);  
        	}
    };
	/**
	 * A call-back for click on a selected item
	 */
    OnItemClickListener mItemListener = new OnItemClickListener() {

		public void onItemClick ( AdapterView  arg0, View arg1, int arg2, long arg3) {
			nextScreen();
			
		}
	};
	
	/**
	 * A call-back for when the user presses the Next button.
	 */
/*
 	OnClickListener mNextListener = new OnClickListener() {
		public void onClick(View v) {
			nextScreen();
		}
	};
*/	
	/**
	 * A call-back for when the user presses the back button.
	 */
/*
	OnClickListener mBackListener = new OnClickListener() {
		public void onClick(View v) {
			finish();
		}
	};
*/
	
	/**
	 * A call-back for when the user presses the clear button.
	 */
	OnClickListener mSettingsListener = new OnClickListener() {
		public void onClick(View v) {
			settingsScreen();
			
		}
	};
	/**
	 * A call-back for when select a route type.
	 */
	OnItemSelectedListener mRouteTypeListener = new OnItemSelectedListener() {
		public void onItemSelected(AdapterView parent, View v, int position, long id){
			routeTypeSelected();
			
		}
		public void onNothingSelected(AdapterView parent){}
	};

	
}